import {Inject, Injectable} from "@nestjs/common";
import {GoodsSaveDto} from "~/modules/shop/goods/goods.dto";
import {UploadService} from "~/modules/tools/upload/upload.service";
import {InjectRepository} from "@nestjs/typeorm";
import {Repository} from "typeorm";
import {GoodsEntity} from "~/modules/shop/goods/goods.entity";

@Injectable()
export class GoodsService {
  @Inject()
  private readonly uploadService: UploadService

  @InjectRepository(GoodsEntity)
  private readonly goodsRepository: Repository<GoodsEntity>

  async save(goodsSaveDto: GoodsSaveDto) {
    const path: string = await this.uploadService.saveFile(goodsSaveDto.file)

    const goods = new GoodsEntity()
    goods.name = goodsSaveDto.name
    goods.price = goodsSaveDto.price
    goods.image = path
    goods.password = goodsSaveDto.password
    goods.description = ""

    return await this.goodsRepository.save(goods)
  }

  async remove(id: number) {
    // 先查询是否存在
    const goods = await this.goodsRepository.findOne({where: {id}})

    // 删除图片图片
    await this.uploadService.removeFile(goods.image)
    await this.goodsRepository.delete(id)
  }

  async find() {
    return await this.goodsRepository.find()
  }
}
